﻿using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Xww.IO.Serialize {
    public class BinarySerializer<T> {
        /// <summary>
        /// 将当前实例保存为二进制文件，泛型方法（类型T必须为ISerializable）
        /// </summary>
        /// <param name="instance">要进行序列化的对象</param>
        /// <param name="fileName">要保存序列化结果的文件路径</param>
        public void SerializeToFileStream(T instance, string fileName) {
            Stream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None);
            SerializeToStream(stream, instance);
            stream.Close();
        }
        /// <summary>
        /// 从二进制文件中读取指定类型的对象
        /// </summary>
        /// <param name="fileName">反序列化的文件名</param>
        /// <returns></returns>
        public T DeserializeFromFileStream(string fileName) {
            Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
            return DeserializeFromStream(stream);
        }
        ///<summary>将指定对象序列化到流中</summary>
        public void SerializeToStream(Stream stream, T instance) {
            IFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, instance);
        }
        ///<summary>从流中反序列化对象</summary>
        public T DeserializeFromStream(Stream stream) {
            IFormatter formatter = new BinaryFormatter();
            return (T)formatter.Deserialize(stream);
        }
    }

    public interface IBinarySerialize<T> {
        void SerializeToFile(string fileName);
        T DeserializeFromFile(string fileName);
    }
}
